package com.g0dkar.leet.core.configuration.loaders;

import java.util.List;

import org.jdom.Element;

import com.g0dkar.leet.core.configuration.LeetConfiguration;
import com.g0dkar.leet.core.model.loaders.ModelLoaderInterface;
import com.g0dkar.leet.util.common.StringUtils;
import com.g0dkar.leet.util.file.FileUtils;
import com.g0dkar.leet.util.reflection.ReflectionUtils;

/**
 * This loader creates {@link LeetConfiguration} based in a XML file (it's root {@link Element} is passed as a
 * parameter to the {@link #load(Element)} method)
 * 
 * @author Rafael M. Lins
 * @see #load(Element)
 * 
 */
public class LeetConfigurationXmlLoader implements ModelLoaderInterface<LeetConfiguration, Element> {
	private LeetConfiguration configuration;
	public LeetConfigurationXmlLoader() {
		configuration = null;
	}
	
	public LeetConfigurationXmlLoader(LeetConfiguration configuration) {
		this.configuration = configuration;
	}
	
	public LeetConfiguration load(Element element) {
		configuration = new LeetConfigurationClassLoader().load(configuration);
		
		configuration.setBaseDir(element.getAttributeValue("baseDir", FileUtils.APPLICATION_DIRECTORY));
		configuration.setBasePackage(element.getAttributeValue("basePackage", configuration.getBasePackage()));
		configuration.setName(element.getAttributeValue("name", configuration.getName()));
		configuration.setDescription(element.getAttributeValue("title", configuration.getDescription()));
		
		if (!StringUtils.isBlank(configuration.getBasePackage())) {
			configuration.addClassMappingPackage(configuration.getBasePackage());
		}
		
		List<Element> classMappingsElements = element.getChildren("class-mapping");
		for (Element cmElement : classMappingsElements) {
			if (!StringUtils.isBlank(cmElement.getAttributeValue("class"))) {
				configuration.addClassMapping(ReflectionUtils.MIRROR.reflectClass(cmElement.getAttributeValue("class")));
			}
			if (!StringUtils.isBlank(cmElement.getAttributeValue("package"))) {
				configuration.addClassMappingPackage(cmElement.getAttributeValue("package"));
			}
		}
		
		return configuration;
	}
}
